package com.xyh.student.service.impl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xyh.student.dao.OptionDao;
import com.xyh.student.dao.QuestionDao;
import com.xyh.student.entity.ExcelToDataBase;
import com.xyh.student.entity.Option;
import com.xyh.student.entity.Question;
import com.xyh.student.entity.ResponseData;
import com.xyh.student.service.QuestionService;

@Service("questionService")
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionDao questionDao;

    @Autowired
    private OptionDao optionDao;

    @Override
    public ResponseData findAllQuestion() {
        try {
            List<Question> questions = questionDao.findAllQuestion();
            return new ResponseData("0", "请求成功", questions);
        } catch (Exception e) {
            System.out.println(e);
            return new ResponseData("888", "请求失败");
        }
    }

    @Override
    public ResponseData insertQuestionAndOption(Question question, Option option) {
        try {
            questionDao.insertQuestion(question);
            if (question.getType() == 1 || question.getType() == 2) {
                int oid = question.getQid();
                option.setOid(oid);
                optionDao.insertOption(option);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("question", question);
            if (option.getOid() != null) {
                question.setOption(option);
                map.put("option", option);
                // System.out.println("???");
            }

            return new ResponseData("0", "请求成功", map);
        } catch (Exception e) {
            System.out.println(e);
            return new ResponseData("888", "请求失败");
        }
    }

    @Override
    public ResponseData toDataBase(ExcelToDataBase excelToDataBase, int liblid) {
        try {
            // String[] questionType = { "单选", "多选", "判断", "填空", "问答" };
            List<Question> single = insertAuto(excelToDataBase, liblid, "单选");
            List<Question> multip = insertAuto(excelToDataBase, liblid, "多选");
            List<Question> estimate = insertAuto(excelToDataBase, liblid, "判断");
            List<Question> gap = insertAuto(excelToDataBase, liblid, "填空");
            List<Question> essay = insertAuto(excelToDataBase, liblid, "问答");
            List<Option> singleOption = insertOptions(excelToDataBase, "单选");
            List<Option> multipOption = insertOptions(excelToDataBase, "多选");
            questionDao.insertQuestionList(single);
            questionDao.insertQuestionList(multip);
            int index = 0;
            for (Question question : single) {
                int qid = question.getQid();
                singleOption.get(index).setOid(qid);
                index++;
            }
            for (Option option : singleOption) {
                //System.out.println(option.getOid());
                optionDao.insertOption(option);
            }
            // optionDao.insertOptionList(singleOption);
            index = 0;
            for (Question question : multip) {
                int qid = question.getQid();
                multipOption.get(index).setOid(qid);
                index++;
            }
            for (Option option : multipOption) {
                //System.out.println(option.getOid());
                optionDao.insertOption(option);
            }
            // optionDao.insertOptionList(multipOption);
            //System.out.println(estimate);
            questionDao.insertQuestionList(estimate);
            //System.out.println(gap);
            questionDao.insertQuestionList(gap);
            //System.out.println(essay);
            questionDao.insertQuestionList(essay);
            //System.out.println(single.toString());
            //System.out.println(singleOption.toString());
            Map <String,Object> map = new HashMap<>();
            List<Question> hasSingle = questionDao.findQuestionByType(1);
            List<Question> hasMultip = questionDao.findQuestionByType(2);
            List<Question> hasEstimate = questionDao.findQuestionByType(3);
            List<Question> hasGap = questionDao.findQuestionByType(4);
            List<Question> hasEssay = questionDao.findQuestionByType(5);
            map.put("single",hasSingle);
            map.put("multip",hasMultip);
            map.put("estimate",hasEstimate);
            map.put("gap",hasGap);
            map.put("essay",hasEssay);
            return new ResponseData("0", "请求成功",map);
        } catch (Exception e) {
            System.out.println(e);
            return new ResponseData("888", "请求失败");
        }
    }

    public List<Question> insertAuto(ExcelToDataBase excelToDataBase, int liblid, String sheetName) {
        try {
            List<Question> questions = new ArrayList<Question>();
            String filePath = excelToDataBase.getFilepath().replace("##", "\\");
            InputStream inputStream = new FileInputStream(filePath);
            try (Workbook workbook = new XSSFWorkbook(inputStream)) {
                Sheet sheet = workbook.getSheet(sheetName);
                //System.out.println(sheetName);
                // Sheet sheet = workbook.getSheetAt(0);
                if (sheet != null) {
                    for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                        Row row = sheet.getRow(rowNum);
                        Question question = new Question();
                        // 题目类容
                        String details = null;
                        if (row.getCell(0) != null) {
                            details = row.getCell(0).getStringCellValue();
                        }
                        // 题目类型
                        int type = 0;
                        if ("单选".equals(sheetName)) {
                            type = 1;
                        } else if ("多选".equals(sheetName)) {
                            type = 2;
                        } else if ("判断".equals(sheetName)) {
                            type = 3;
                        } else if ("填空".equals(sheetName)) {
                            type = 4;
                        } else if ("问答".equals(sheetName)) {
                            type = 5;
                        }
                        // 题目难度
                        String difficulty = null;
                        int difficulty1 = 0;
                        if (row.getCell(1) != null) {
                            difficulty = row.getCell(1).getStringCellValue();
                            difficulty = difficulty.replace(",", "");
                            difficulty1 = Integer.parseInt(difficulty);
                        }
                        // 题目答案
                        String answer = row.getCell(2).getStringCellValue();
                        // 题目来源
                        String source = null;
                        int source1 = 1;
                        if (row.getCell(3) != null) {
                            source = row.getCell(3).getStringCellValue();
                            // System.out.println(source);
                            if (source.equals("第三方")) {
                                source1 = 2;
                            } else if (source.equals("原创")) {
                                source1 = 1;
                            }
                        }
                        // System.out.println(source1);
                        // 题目分数
                        String score = null;
                        int score1 = 0;
                        if (row.getCell(4) != null) {
                            score = row.getCell(4).getStringCellValue();
                            score = score.replace(",", "");
                            score1 = Integer.parseInt(score);
                        }
                        question.setDetails(details);
                        question.setType(type);
                        question.setDifficulty(difficulty1);
                        question.setAnswer(answer);
                        question.setSource(source1);
                        question.setLid(liblid);
                        question.setScore(score1);
                        questions.add(question);
                    }
                    // System.out.println(questions.toString());
                }
            }
            return questions;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    public List<Option> insertOptions(ExcelToDataBase excelToDataBase, String sheetName) {
        try {
            List<Option> options = new ArrayList<Option>();
            String filePath = excelToDataBase.getFilepath().replace("##", "/");
            InputStream inputStream = new FileInputStream(filePath);
            try (Workbook workbook = new XSSFWorkbook(inputStream)) {
                Sheet sheet = workbook.getSheet(sheetName);
                // Sheet sheet = workbook.getSheetAt(0);
                if (sheet != null) {
                    for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                        Row row = sheet.getRow(rowNum);
                        Option option = new Option();
                        // A~G
                        String ad = null;
                        String bd = null;
                        String cd = null;
                        String dd = null;
                        String ed = null;
                        String fd = null;
                        String gd = null;
                        if (row.getCell(5) != null) {
                            ad = row.getCell(5).getStringCellValue();
                        }
                        if (row.getCell(6) != null) {
                            bd = row.getCell(6).getStringCellValue();
                        }
                        if (row.getCell(7) != null) {
                            cd = row.getCell(7).getStringCellValue();
                        }
                        if (row.getCell(8) != null) {
                            dd = row.getCell(8).getStringCellValue();
                        }
                        if (row.getCell(9) != null) {
                            ed = row.getCell(9).getStringCellValue();
                        }
                        if (row.getCell(10) != null) {
                            fd = row.getCell(10).getStringCellValue();
                        }
                        if (row.getCell(11) != null) {
                            gd = row.getCell(11).getStringCellValue();
                        }
                        option.setAd(ad);
                        option.setBd(bd);
                        option.setCd(cd);
                        option.setDd(dd);
                        option.setEd(ed);
                        option.setFd(fd);
                        option.setGd(gd);
                        options.add(option);
                    }

                }
            }
            return options;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    @Override
    public ResponseData findQuestionByLid(int lid) {
        try {
            List<Question> questions = questionDao.findQuestionByLid(lid);
            return new ResponseData("0", "请求成功",questions);
        } catch (Exception e) {
            return new ResponseData("888", "请求成功");
        }
    }

    @Override
    public ResponseData deleteById(int qid) {
        try {
            questionDao.deleteById(qid);
            return new ResponseData("0", "删除成功");
        } catch (Exception e) {
            return new ResponseData("888", "删除失败");
        }
    }

    @Override
    public ResponseData findQuestionById(int qid) {
        try {
            Question question = questionDao.findQuestionByQid(qid);
            return new ResponseData("0", "请求成功",question);
        } catch (Exception e) {
            return new ResponseData("888", "请求失败");
        }
    }

    

}
